package net.xiangcaowuyu.example1.controller;

import net.xiangcaowuyu.example1.dao.SysUserRepository;
import net.xiangcaowuyu.example1.domain.SysUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Optional;

/**
 * 博客：https://www.xiangcaowuyu.net
 * Description:
 *
 * @Author: 香草物语
 * DateTime: 2021-07-21 15:07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private SysUserRepository sysUserRepository;

    @Value("${person.name}")
    public String personName;

    @GetMapping("/findAll")
    @Transactional
    public List<SysUser> findAll() {
        System.out.println(personName);
        return sysUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate p1 = criteriaBuilder.like(root.get("nickName"), "%超级%");
            Predicate p2 = criteriaBuilder.equal(root.get("userName"), "admin");
            Predicate p3 = criteriaBuilder.equal(root.get("email"), "ry@163.com");
            Predicate p4 = criteriaBuilder.equal(root.get("userId"), 1);
            return criteriaBuilder.and(p4, criteriaBuilder.and(p3, criteriaBuilder.or(p1, p2)));
        });
    }

    @GetMapping("/save")
    @Transactional(readOnly = true,propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    public SysUser save() {
        Optional<SysUser> sysUserOptional = sysUserRepository.findById(1L);
        sysUserOptional.get().setNickName("哈哈");
        SysUser sysUser = sysUserRepository.save(sysUserOptional.get());
        List<SysUser> sysUserList = findAll();
        return sysUser;
    }

}
